import * as $dataform from '@/management/api/dataform'
import * as $collect from '@/management/api/dataform-collect'
import { CODE_MAP } from '@/management/api/eco/base'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/src/message.scss'
// import { getSurveyList as surveyList } from '@/management/api/survey'
import { set } from 'lodash-es'
import { BusineType, FormType, templateMenus } from '@/management/utils/types/formsTypes'

export default {
  namespaced: true,
  state: {
    // 分类管理
    busineType: BusineType.All,
    optionMenus: templateMenus,
   
    formType: FormType.System,
    formsList: [], // 活动列表
    formsTotal: 0,
    formsHasMore: true,
    formDetail: null,
    directoryList: [],
    
    workspaceId: '-1',
    spaceDetail: null,
    teamSpaceList: [],
    // 列表管理
    surveyList: [],
    surveyTotal: 0,
    searchVal: '',
    selectValueMap: {
      busineType: '',
      'status': ''
    },
    buttonValueMap: {
      lastModifyTime: '',
      // createTime: -1
    }
  },
  getters: {
    listFliter(state) {
      return [
        {
          comparator: '',
          condition: [
            {
              field: 'formName',
              value: state.searchVal,
              comparator: '$regex'
            }
          ]
        },
        {
          comparator: '',
          condition: [
            {
              field: 'status',
              value: state.selectValueMap['status']
            }
          ]
        }
        // {
        //   comparator: '',
        //   condition: [
        //     {
        //       field: 'busineType',
        //       value: state.selectValueMap.busineType
        //     }
        //   ]
        // }
      ]
    },
    listOrder(state) {
      const { buttonValueMap } = state
      return Object.entries(buttonValueMap)
        .filter(([, effectValue]) => effectValue)
        .reduce((prev, item) => {
          const [effectKey, effectValue] = item
          prev.push({ field: effectKey, value: effectValue })
          return prev
        }, [])
    }
  },
  mutations: {
    changeFormType(state, formType) {
      state.formType = formType
    },
    changeBusineType(state, busineType) {
      // 切换操作类型清除筛选条件
      this.commit('dataform/reserSelectValueMap')
      this.commit('dataform/reserButtonValueMap')
      this.commit('dataform/setSearchVal', '')
      state.busineType = busineType
    },
    setFormDetail(state, data) {
      state.formDetail = data
    },
    setFormsList(state, list) {
      state.formsList = list
    },

    setDirectoryList(state, list) {
      state.directoryList = list
    },
    setFormsTotal(state, total) {
      state.formsTotal = total
    },

    setFormsHasMore(state, hasMore) {
      state.formsHasMore = hasMore
    },

    setSearchVal(state, data) {
      state.searchVal = data
    },
    reserSelectValueMap(state) {
      state.selectValueMap = {
        busineType: '',
        status: ''
      }
    },
    changeSelectValueMap(state, { key, value }) {
      state.selectValueMap[key] = value
    },
    reserButtonValueMap(state) {
      state.buttonValueMap = {
        lastModifyTime: '',
        // createTime: -1
      }
    },
    changeButtonValueMap(state, { key, value }) {
      state.buttonValueMap[key] = value
    },

    changeWorkSpace(state, workSpaceId) {
      // 切换空间清除筛选条件
      this.commit('dataform/reserSelectValueMap')
      this.commit('dataform/reserButtonValueMap')
      this.commit('dataform/setSearchVal', '')
      state.workSpaceId = workSpaceId
    },
    setSpaceDetail(state, data) {
      state.spaceDetail = data
    },
    updateSpaceMenus(state, teamSpace) {
      // 更新空间列表下的团队空间
      set(state, 'optionMenus[1].children', teamSpace)
    },
  },
  actions: {
    async addCollect({}, params) {
      const res = await $collect.save({
        formId: params.formId
      })

      if (res.serverResult.resultCode === CODE_MAP.SUCCESS) {
        ElMessage.success('添加成功')
      } else {
        ElMessage.error(res.serverResult.resultMessage)
      }
    },
    async delCollect({}, params) {
      const res = await $collect.del({
        formId: params.formId
      })

      if (res.serverResult.resultCode === CODE_MAP.SUCCESS) {
        ElMessage.success('添加成功')
      } else {
        ElMessage.error(res.serverResult.resultMessage)
      }
    },
    async deleteForm({}, params) {
      const res = await $dataform.del({
        formId: params.formId
      })

      if (res.serverResult.resultCode === CODE_MAP.SUCCESS) {
        ElMessage.success('删除成功')
      } else {
        ElMessage.error(res.serverResult.resultMessage)
      }
    },
    async copyForm({}, params) {
      const res = await $dataform.del({
        formId: params.formId
      })

      if (res.serverResult.resultCode === CODE_MAP.SUCCESS) {
        ElMessage.success('复制成功')
      } else {
        ElMessage.error(res.serverResult.resultMessage)
      }
    },
    async getFormDetail({ state, commit }, id) {
      try {
        const busineType = id || state.busineType
        const res = await $dataform.get(busineType)
        if (res.serverResult.resultCode === CODE_MAP.SUCCESS) {
          commit('setFormDetail', res.data)
        } else {
          ElMessage.error(res.serverResult.resultMessage)
        }
      } catch (err) {
        ElMessage.error('getSpaceList' + err)
      }
    },
    async getFormsList({ state, getters, commit }, payload) {
      if (!state.formsHasMore) {
        return
      }
      let condition = {
        // busineType: state.busineType,
        formType: FormType.System
      }

      getters.listFliter.filter((item) => {
        return item.condition[0].value
      }).forEach((item) => {
        condition[item.condition[0].field] = item.condition[0].value
      })
      
      let orderString = ['busineType asc']

      try {
        let params = {
          pageNo: payload?.curPage || 1,
          pageSize: payload?.pageSize || 1000, // 默认一页10条
          orderList: orderString,
          condition: condition
        }

        const res = await $dataform.list(params)
        if (res.serverResult.resultCode === CODE_MAP.SUCCESS) {
          let originlist = (res?.result?.list || [])
          let list = originlist.map((item, index) => {
            let tmp = {
              _id: item.formId,
              ...item
            }
            if (index === 0) {
              tmp.idkey = item.busineType
            } else if (originlist[index - 1].busineType !== item.busineType) {
              tmp.idkey = item.busineType
            }

            return tmp
          }) || []


          let currenPage = res?.result?.currentPageNo || 0

          commit('setFormsList', list)
          commit('setFormsTotal', currenPage)
        } else {
          ElMessage.error(res.serverResult.resultMessage)
        }
      } catch (error) {
        console.log(error)
      }
    }
  }
}
